package com.aisi.backend.utils;

import cn.hutool.core.lang.UUID;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;

/**
 * @Author: shenjianZ
 * @Date: 2024/4/30 下午10:51
 * @Description:
 */


public class JwtUtils {

    public static String key = "CheerTrail";
    public static int expire = 3;

    /**
     * 创建JWT令牌
     *
     * @param id       用户id
     * @param username 用户名
     * @return 令牌
     */
    public static String createJwtToken(Integer id, String username) {
        Date expireTime = expireTime(); // JWT令牌的过期时间
        Date nowTime = new Date();       // JWT令牌颁发时间
        Algorithm algorithm = Algorithm.HMAC256(key); // 加密方式
        // 创建jwt令牌
        return JWT.create()
                .withJWTId(UUID.randomUUID().toString()) // 设置类型
                .withClaim("id", id) // 自定义参数
                .withClaim("username", username) // 自定义参数
                .withExpiresAt(expireTime) // 设置过期时间
                .sign(algorithm); // 设置加密方式
    }

    /**
     * 计算颁发JWT令牌的过期时间
     *
     * @return Date 过期时间
     */
    public static Date expireTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, expire * 24);
        return calendar.getTime();
    }

    public static Long getJWTExpireTime(String token) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        Date expiresAt = jwt.getExpiresAt();
        return (Long) expiresAt.getTime();
    }


    /**
     * 解析JWT令牌
     *
     * @param token 令牌
     * @return 解析后的Token
     * Const.TOKEN_VALID：有效
     * Const.TOKEN_EXPIRE：过期
     * Const.TOKEN_INVALID：无效
     */
    public static String resolveJwtToken(String token) {
        token = token.replace("Bearer ", "");
        Algorithm algorithm = Algorithm.HMAC256(key);
        JWTVerifier verifier = JWT.require(algorithm).build();
        try {
            DecodedJWT verify = verifier.verify(token);   // 在try catch中检查令牌是否被篡改
            Date expiresAt = verify.getExpiresAt();
            Date nowTime = new Date();
            return expiresAt.after(nowTime) ? Const.TOKEN_VALID : Const.TOKEN_EXPIRE;
        } catch (Exception e) {
            return Const.TOKEN_INVALID;
        }
    }
    public static Integer getJWTUserId(String token) {
        Algorithm algorithm = Algorithm.HMAC256(key);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        return (Integer) jwt.getClaim("id").asInt();
    }

}
